<template>
  <div class="task-dialog">
    <el-dialog :visible.sync="dialogFormVisible"
               :append-to-body="true"
               :close-on-click-modal="false"
               class="custom-task-dialog"
               @close="close"
               @open="open">
      <div slot="title">
        <div style="color:#fff">{{title}}</div>
      </div>
      <el-form :model="taskForm" :rules="taskRules" ref="taskForm">
        <el-form-item label="农事类型" :label-width="formLabelWidth" prop="type">
          <el-radio-group v-model="taskForm.type" size="small">
            <el-radio-button v-for="item in typeOptions" :key="item.formCode" :label="item.formCode">{{item.formName}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="处理开始时间" :label-width="formLabelWidth" prop="handleStartTime">
          <el-date-picker
            v-model="taskForm.handleStartTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择接入时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="处理结束时间" :label-width="formLabelWidth" prop="handleEndTime">
          <el-date-picker
            v-model="taskForm.handleEndTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择接入时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="操作建议" :label-width="formLabelWidth" prop="remarks">
          <el-input v-model.trim="taskForm.remarks"
                    style="width:100%"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入操作建议"/>
        </el-form-item>
      </el-form>
      <div slot="footer" style="margin-top:-20px">
        <el-button type="primary" @click="handleClickSubmit" :loading="addStatus">完&nbsp;&nbsp;成
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
    import PubSub from 'pubsub-js'
    import {
        FARM_TASK_ADD_INFO,
        FARM_TASK_DETAIL_REFRESH
    } from '@/utils/publishId'
    import {
        batchSaveTasks
    } from '@/api/affairs'
    export default {
        data() {
            const validateStartTime = (rule, value, callback) => {
                if (value == null || value == '' || value == undefined) {
                    callback(new Error('起始时间不能为空'))
                } else {

                    if(this.taskForm.handleEndTime && this.taskForm.handleEndTime!=''){
                        let starTime = new Date(this.taskForm.handleStartTime).getTime()
                        let endTime = new Date(this.taskForm.handleEndTime).getTime()
                        if(endTime<=starTime){
                            this.taskForm.handleStartTime = ""
                            callback(new Error('起始时间不能大于结束时间'))
                        }
                    }
                    callback()
                }
            }
            const validateEndTime = (rule, value, callback) => {
                if (value == null || value == '' || value == undefined) {
                    callback(new Error('结束时间不能为空'))
                } else {

                    if(this.taskForm.handleStartTime && this.taskForm.handleStartTime!=''){
                        let starTime = new Date(this.taskForm.handleStartTime).getTime()
                        let endTime = new Date(this.taskForm.handleEndTime).getTime()
                        if(endTime<=starTime){
                            this.taskForm.handleEndTime = ""
                            callback(new Error('结束时间不能小于起始时间'))
                        }
                    }
                    callback()
                }
            }
            return {
                massId:"", //详情地块id
                type:"",
                title: "",
                addStatus:false,
                dialogFormVisible: false,
                formLabelWidth: "110px",
                typeOptions:[],
                addType:"",
                taskForm:{
                    key:"",
                    type:"",
                    handleStartTime:"",
                    handleEndTime:"",
                    remarks:""
                },
                taskRules: {
                    type:[
                        {required: true, message: '请选择类型', trigger: 'change'}
                    ],
                    handleStartTime:[
                        {required: true, message: '处理开始时间不能为空', trigger: 'change'},
                        {validator: validateStartTime, trigger: 'blur'}
                    ],
                    handleEndTime:[
                        {required: true, message: '处理结束时间不能为空', trigger: 'change'},
                        {validator: validateEndTime, trigger: 'blur'}
                    ],
                    remarks:[
                        {required: true, message: '操作建议不能为空', trigger: 'blur'},
                        {min: 1, max: 150, message: '长度在 1 到 150 个字符', trigger: 'blur'}
                    ]
                },
            }
        },
        methods: {
            show(status, type, obj, massId) {
                this.massId = massId
                this.type = type
                switch (type) {
                    case "add":
                        this.typeOptions = obj
                        this.title = "添加任务"
                        this.addType = ""
                        break;
                    case "detail_add":
                        this.typeOptions = obj
                        console.log("this.typeOptions",this.typeOptions)
                        this.title = "添加任务"
                        this.addType = "detail_add"
                        break;
                    case "edit":
                        this.title = "编辑任务"
                        this.typeOptions = obj.taskList
                        setTimeout(()=>{
                            this.taskForm = {
                                key: obj.taskItem.key,
                                type:obj.taskItem.farmType,
                                handleStartTime:obj.taskItem.startTime,
                                handleEndTime:obj.taskItem.endTime,
                                remarks:obj.taskItem.proposal
                            }
                        },100)
                        break;
                }
                this.dialogFormVisible = status
            },
            handleClickSubmit(){
                this.$refs.taskForm.validate((valid) => {
                    if (valid) {
                        if(this.addType==''){
                            PubSub.publish(FARM_TASK_ADD_INFO, {
                                type:this.type,
                                info: this.$cloneDeep(this.taskForm)
                            })
                        }else if(this.addType=='detail_add'){
                            const formData = this.$cloneDeep(this.taskForm)
                            const params = [{
                                    farmType:formData.type,
                                    startTime:formData.handleStartTime,
                                    endTime:formData.handleEndTime,
                                    proposal:formData.remarks,
                            }]
                            batchSaveTasks({
                                tasks: params,
                                ids:[this.massId]
                            }).then(res=>{
                                if(res.data.code && res.data.code==200){
                                    this.$message({type:"success", message:res.data.msg})
                                }else{
                                    this.$message({type:"error", message:res.data.msg})
                                }
                                PubSub.publish(FARM_TASK_DETAIL_REFRESH, {
                                    type:this.type
                                })
                                this.addStatus = false
                                this.dialogFormVisible = false
                                console.log("id", this.massId, params)
                            }).catch(err=>{
                                this.addStatus = false
                                this.dialogFormVisible = false
                                this.$message({type:"error", message:"批量添加报错："+err})
                            })
                        }
                    }else {
                        console.log('error submit!!')
                        return false
                    }
                })
            },

            open() {
                this.$nextTick(()=>{
                    try{
                        this.$refs.taskForm.resetFields()
                        this.$refs.taskForm.clearValidate()
                    }catch (e) {}
                })
            },
            close() {
                Object.assign(this.$data.taskForm, this.$options.data().taskForm)
                this.$refs.taskForm.resetFields()
                this.$refs.taskForm.clearValidate()
            }

        }
    }
</script>

<style scoped>
  .custom-task-dialog >>> .el-dialog {
    width: 900px !important;
    position: relative;
  }

  .custom-task-dialog >>> .el-dialog__header {
    background: #009865;
    padding: 10px 10px 10px;
  }

  .custom-task-dialog >>> .el-dialog__headerbtn {
    top: 9px !important;
    right: 10px !important;
  }

  .custom-task-dialog >>> .el-dialog__body {
    line-height: 0px !important;
  }

  .custom-task-dialog >>> .el-input.is-disabled .el-input__inner {
    background-color: #fff;
    color: #606266;
  }

  .custom-task-dialog >>> .el-textarea.is-disabled .el-textarea__inner {
    background-color: #fff;
    color: #606266;
  }
</style>
